<template>
    <div class="course-container">
        <div>
<!--            课程信息-->
            <div v-if="course && course.teacher" class="course-info">
                <el-row :gutter="20" justify="center">
                    <el-col :span="8">
                        <div class="course-image">
                            <image-preview :src="course.imgs" />
                        </div>
                        <div class="rating">
                            <div style="font-size: 12px;margin-right: 10px;">
                                课程推荐指数
                            </div>
                            <el-rate
                                    v-model="rating"
                                    disabled
                                    show-score
                                    text-color="#ff9900"
                                    score-template="{value} points"
                            />
                        </div>
                    </el-col>

                    <el-col :span="16">

                        <h1 style="font-size: 22px">{{ course.name }}</h1>
                        <div class="fontsize">
                            <span >主讲人: <span style="color: #1c4cc6">  {{ course.teacher.userName }}</span></span>
                            <span >学期: {{ course.term }}</span>
                        </div>
                        <div  class="bgclassinfo">
                            <span>学时: {{ course.hours }}</span>
                            <span>学分: {{ course.credits }}</span><br>
<!--                            <p><strong>选课人数: </strong> {{ course.nownum }}</p>-->
                            <span>教室地址: {{ course.classroom }}</span>
                            <span>总人数: {{ course.maxnum }}</span><br>
                            <span>开始时间: {{ course.starttime }}</span>
                            <span>结束时间: {{ course.endtime }}</span>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>

        <div class="my-answers">
            <div class="title underline">
                课堂问题
            </div>
            <div class="answer-items">
                       <div v-if="questionList.length" class="answer-item" v-for="question in questionList" :key="question.id" >
                       <div class="label">问题题目:</div>
                       <div class="answer-title">
                           <span class="indent"></span>
                           {{ question.title }}
                       </div>
                       <div class="label">问题内容:</div>

                       <div class="answer-description">
                           <span class="indent"></span>
                           {{ question.content }}
                       </div>
                       <div class="label">问题分数:</div>
                       <div class="answer-score">
                           <span class="indent"></span>
                           {{ question.answerscore }}
                       </div>
                       <div>
                           <div class="label">我的回答:</div>
                           <el-input
                                   type="textarea"
                                   :rows="2"
                                   placeholder="请输入您的回答"
                                   v-model="question.studentanswer"
                                   :disabled="isSubmitted[question.id]"
                                   maxlength="500"
                                   show-word-limit
                           />
                       </div>
                       <!--                    提交,重置-->
                       <div class="answer-submit">
                           <el-button  :disabled="isSubmitted[question.id]" @click="resetAnswer(question)">清空</el-button>
                           <el-button type="primary"  :disabled="isSubmitted[question.id]" @click="submitAnswer(question)">提交</el-button>
                       </div>
                   </div>
                   <div v-else class="no-courses-message">这门课还没有课堂问题~</div>

            </div>
        </div>

        <div class="my-exams">
            <div class="title underline">
                课堂成绩
            </div>
            <el-table :data="questionList">
                <el-table-column prop="title" label="问题题目" />
                <el-table-column label="我的回答">
                    <template #default="scope">
                        <!-- 使用三元运算符处理 studentanswer 可能为空的情况 -->
                        <span>{{ scope.row.studentanswer || '暂无' }}</span>
                    </template>
                </el-table-column>
                <!-- 正确答案 -->
                <el-table-column label="正确答案" align="center" width="500">
                    <template #default="scope">
                        <!-- 使用三元运算符处理 answer 可能为空的情况 -->
                        <div class="content-div" v-html="scope.row.answer || '暂无'"></div>
                    </template>
                </el-table-column>
                <!-- 得分 -->
                <!--    <el-table-column  prop="answerscore" label="得分"  />-->
            </el-table>

        </div>

    </div>
</template>

<script setup>
    import { onBeforeMount, ref, computed,onMounted } from 'vue';
    import { useRoute } from 'vue-router';
    import { ElMessage } from 'element-plus'; // 确保你已经安装并引入了 element-plus
    import { getMyCourse ,listQuestion,updateQuestion} from '@/api/MyCourse/MyCourse';
    const course = ref([]);
    const route = useRoute();
    const courseId = ref(route.params.id);
    const questionList = ref([]);
    const userId = localStorage.getItem('userId');
    const { proxy } = getCurrentInstance();
    const isSubmitted = ref({});


    /** 获取课程信息*/
    onBeforeMount(() => {
        getMyCourse(courseId.value).then(response => {
            if (response.data) {
                course.value = response.data;
            }
        });
    });
    onMounted(() => {
        fetchData();
    });
    //获取成绩
    const fetchData = () => {
        listQuestion({ courseId: courseId.value }).then(response => {
            if (response.rows && Array.isArray(response.rows)) {
                questionList.value = response.rows.map(question => {
                    // 初始化 isSubmitted 的状态
                    isSubmitted.value[question.id] = !!question.studentanswer;
                    //如果回答内容为空，就不返回答案和分数
                    if (!question.studentanswer) {
                        delete question.answer;
                        // delete question.answerscore;
                    }
                    return question;
                });
            }
        });
    };
    // 提交回答的函数
/*    const submitAnswer = (question) => {
        // 构建数据对象
        const data = {
            id: question.id,
            studentanswer: question.studentanswer,
            userId: userId,
        };

        updateQuestion(data)
            .then(() => {
                // 更新提交标志
                proxy.$modal.confirm('请确定您的回答,提交后不可修改!')
                    .then(() => {
                        proxy.$modal.msgSuccess('提交成功');
                        isSubmitted.value[question.id] = true;
                    })
                    .catch(() => {
                        proxy.$modal.msgWarning('已取消提交');
                    });
                // 刷新数据
                fetchData();
            })
            .catch((error) => {
                console.error('提交回答失败', error);
            });
    };*/
    const submitAnswer = (question) => {
        // 构建数据对象
        const data = {
            id: question.id,
            studentanswer: question.studentanswer,
            userId: userId,
        };
        proxy.$modal.confirm('请确定您的回答,提交后不可修改!')
            .then(() => {
                updateQuestion(data)
                    .then(() => {
                        // 用户点击了确认，更新提交标志
                        isSubmitted.value[question.id] = true;
                        // 显示成功消息
                        proxy.$modal.msgSuccess('提交成功');
                        fetchData();
                    })
                    .catch(() => {
                        // 用户点击了取消，不做任何操作
                        proxy.$modal.msgWarning('已取消提交');
                        fetchData();
                    });
            })
            .catch((error) => {
                console.error('提交回答失败', error);
            });
    };

    //清空按钮
    const resetAnswer = (question) => {
        if (isSubmitted.value[question.id]) {
            // 如果答案已经提交，询问用户是否真的想清空
            proxy.$modal.confirm('您确定要清空已提交的回答吗？')
                .then(() => {
                    // 用户确认清空
                    question.studentanswer = '';
                    // 清除提交标志，使输入框和按钮再次可用
                    delete isSubmitted.value[question.id];
                })
                .catch(() => {
                    // 用户取消操作
                });
        } else {
            // 如果有内容就清空，否则不做任何操作
            if (question.studentanswer) {
            proxy.$modal.confirm('您确定要清空回答吗？')
                .then(() => {
                    question.studentanswer = '';
                })
                .catch(() => {
                    // 用户取消操作
                    return;
                });
            }
        }
    };

    // 根据ID生成随机评分的方法
    function generateRandomRating(id) {
        // 生成一个3到5之间的随机数，包括3和5
        const randomNum = Math.random() * (5 - 3) + 3;
        // 保留小数点后一位
        return parseFloat(randomNum.toFixed(1));
    }
    // 使用ID生成评分
    const rating = ref(generateRandomRating(courseId.value));
    // 监听ID的变化，以便更新评分
    watch(courseId, () => {
        rating.value = generateRandomRating(courseId.value);
    });





</script>
<style scoped>
    .no-courses-message {
        text-align: center;
        font-size: 1.8em;
        color: #888;
        margin-top: 50px;
    }
    .content-div {
        height: 150px;
        overflow: hidden; /* 隐藏溢出的内容 */
        /*垂直居中*/

        /*    添加滚轮*/
        overflow-y: auto;
        overflow-x: auto;
    }
    .el-row {
        margin-bottom: 20px;
    }
    .el-row:last-child {
        margin-bottom: 0;
    }
    .el-col {
        border-radius: 4px;
    }

    .grid-content {
        border-radius: 4px;
        min-height: 36px;
    }

    .course-container {
        max-width: 1200px;
        margin: 0 auto;
    }

    .course-info {
        margin-top: 20px;
        padding: 20px;
        /*    只要下方边框阴影*/
        box-shadow: 0 10px 4px rgba(0, 0, 0, 0.1);
    }

    .course-image {
        text-align: center;
        width: 100%;
        height: auto;
    }

    .fontsize{
        font-size: 14px;
        margin: 50px 0px 30px 0px;
    }
    .fontsize span{
        margin-right: 35px;
    }
    .bgclassinfo {
        display: flex; /* 启用 Flexbox */
        flex-wrap: wrap; /* 允许换行 */
        background-color: #f5f5f5;
        padding: 20px;
        height: auto; /* 设置为自动以适应内容高度 */
        border-radius: 10px;
        justify-content: space-between; /* 使元素在容器中左右分布 */
    }

    .bgclassinfo span {
        flex-basis: calc(50% ); /* 每个元素占据一半的宽度减去一定的间距 */
        margin-bottom: 10px; /* 在每个元素底部添加间距 */
        display: flex; /* 内部也使用 Flexbox */
        align-items: center; /* 上下居中对齐 */
        font-size: 14px; /* 可以自定义字体大小 */
    }

    /* 如果需要的话，可以添加媒体查询以适应不同屏幕尺寸 */
    @media (max-width: 600px) {
        .bgclassinfo span {
            flex-basis: 100%; /* 在小屏幕设备上，每个元素占据整行 */
        }
    }

    .rating {
        margin-top: 10px;
        text-align: center;
    }

    .my-answers,
    .my-exams {
        margin: 20px 0;
        padding: 20px;
        background-color: #fff;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .title {
        font-size: 1.2em;
        color: #3a8ee6;
        margin-bottom: 10px;
    }

    .underline {
        border-bottom: 1px solid #ccc;
        display: inline-block;
        padding-bottom: 5px;
    }

    .rating-score {
        display: flex;
        align-items: center;
    }

    .remaining-points {
        margin-left: 10px;
    }
    .answer-items {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(30%, 1fr));
        gap: 10px;
        height: 50vh;
        overflow-y: auto;
    }

    .answer-item {
        flex-basis: 30%; /* 每个元素占据30%的宽度 */
        padding: 15px;
        background-color: #f5f5f5;
        border: 1px solid #ccc;
        border-radius: 8px;
        box-sizing: border-box;
        margin: 10px;

    }

    .label {
        font-weight: bold;
        color: #555;
    }
    .indent {
        display: inline-block;
        width: 1.5em; /* 或者你喜欢的任何其他长度单位 */
    }

    /* 为了适应小于一定宽度的屏幕，可以添加媒体查询 */
    @media (max-width: 768px) {
        .answer-item {
            flex: 0 0 100%; /* 在较小的屏幕上，每个元素占据100%的宽度 */
        }
        .answer-items {
            grid-template-columns: 1fr;
        }
    }

    /* 使内部 div 当内容过长时自动换行 */
    .answer-title,
    .answer-description,
    .answer-score {
        margin-top: 5px;
        margin-bottom: 3px;
        margin-left: 30px;
        font-size: 16px;
        word-wrap: break-word; /* 自动换行 */
        overflow-wrap: break-word; /* 自动换行 */
        hyphens: auto; /* 自动连字符断词 */
        white-space: pre-line; /* 保留空格和换行符，同时允许换行 */
    }
    .answer-submit{
        margin-top: 10px;
        margin-bottom: 3px;
    /*    位置偏右*/
        margin-left: 180px;
    }


</style>